package xcmg.device.web.sale;

import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import xcmg.device.dao.entity.company.CompanyInfoDO;
import xcmg.device.dao.mapper.CompanyInfoMapper;
import xcmg.device.dao.mapper.SaleIntentionMapper;
import xcmg.device.infra.AuthCode;
import xcmg.device.infra.BasicController;
import xcmg.device.infra.ErrorCode;
import xcmg.device.service.ExternalParamCheckService;
import xcmg.device.service.sale.ReturnApplyService;
import xcmg.device.service.vo.ExternalParamCheckVO;
import xcmg.device.service.vo.FunctionResult;
import xcmg.device.service.vo.salesReturn.*;
import yb.ecp.fast.infra.annotation.FastMappingInfo;
import yb.ecp.fast.infra.infra.ActionResult;
import yb.ecp.fast.infra.infra.PageCommonVO;
import yb.ecp.fast.infra.infra.SearchCommonVO;
import yb.ecp.fast.infra.infra.log.LogHelper;
import yb.ecp.fast.infra.util.ListUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

/**
 * 退货申请
 * Created by LiChangjiang on 2018/3/6 0006.
 */
@RequestMapping("/returnApply")
@RestController
public class ReturnApplyController extends BasicController
{
    @Autowired
    private ReturnApplyService returnApplyService =null;

    @Autowired
    private CompanyInfoMapper companyInfoMapper=null;

    @Autowired
    private ExternalParamCheckService externalParamCheckService;

    @Autowired
    private SaleIntentionMapper saleIntentionMapper;

    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ApiOperation(value = "查询退货申请列表")
    @FastMappingInfo(needLogin = true)
    public ActionResult list(@RequestBody SearchCommonVO<SalesReturnApplyVO> condition) throws Exception
    {
        if (null == condition)
        {
            return actionResult(ErrorCode.IllegalArument);
        }

        if (null == condition.getFilters())
        {
            SalesReturnApplyVO filters = new SalesReturnApplyVO();
            filters.setSupplierOrgId(getOrgId());
            condition.setFilters(filters);
        }
        else
        {
            condition.getFilters().setSupplierOrgId(getOrgId());
        }

        PageCommonVO pageCommonVO = returnApplyService.list(condition);
        return actionValueResult(pageCommonVO.getPageInfo());
    }


    @RequestMapping(value = "/item", method = RequestMethod.GET)
    @ApiOperation(value = "查询退货申请详情信息")
    @FastMappingInfo(needLogin = true)
    public ActionResult item(@RequestParam("id")  String id) throws Exception
    {
        if (StringUtils.isEmpty(id))
        {
            return actionResult(ErrorCode.IllegalArument);
        }
        return actionValueResult(returnApplyService.item(id));
    }

    @RequestMapping(value = "/remove", method = RequestMethod.POST)
    @ApiOperation(value = "删除退货申请详情信息")
    @FastMappingInfo(needLogin = true,code = AuthCode.ClientApply.RETURN_APPLY_DEL)
    public ActionResult remove(@RequestBody List<String> ids) throws Exception
    {
        if (ListUtil.isNullOrEmpty(ids))
        {
            return actionResult(ErrorCode.IllegalArument);
        }
        return actionResult(returnApplyService.remove(ids));
    }

    @RequestMapping(value = "/audit", method = RequestMethod.POST)
    @ApiOperation(value = "审核退货申请")
    @FastMappingInfo(needLogin = true,code = AuthCode.ClientApply.RETURN_APPLY_AUDIT)
    public ActionResult audit(@RequestBody SalesReturnApplyAddVO applyAddVO) throws Exception
    {
        if (null==applyAddVO)
        {
            return actionResult(ErrorCode.IllegalArument);
        }
        try {
            return actionResult(returnApplyService.auditReturnApply(applyAddVO, getUserId(), getUserName()));
        }catch (Exception e){
            return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
        }
//        return actionResult(returnApplyService.audit(auditVO));
    }

//    @RequestMapping(value = "/addApp", method = RequestMethod.POST)
//    @ApiOperation(value = "添加退货申请")
//    @FastMappingInfo(needLogin = true,code = AuthCode.ClientApply.RETURN_APPLY_ADD)
//    public ActionResult add(@RequestBody SalesReturnApplyAddVO applyAddVO) throws Exception
//    {
//        applyAddVO.setUserId(getUserId());
//        applyAddVO.setUserName(getUserName());
//        applyAddVO.setDeptName(getDeptName());
//        return actionResult(returnApplyService.add(applyAddVO));
//    }

    @RequestMapping(value = "/exportAll", method = {RequestMethod.POST, RequestMethod.GET})
    @ApiOperation(value = "导出所有退货入库单")
    @FastMappingInfo(needLogin = true,code = AuthCode.ClientApply.RETURN_APPLY_EXPORT)
    public void exportAll(SalesReturnApplyVO condition) throws Exception
    {
        if (null == condition)
        {
            condition = new SalesReturnApplyVO();
            condition.setSupplierOrgId(getOrgId());
        }
        else
        {
            condition.setSupplierOrgId(getOrgId());
        }
        returnApplyService.exportAll(condition);
    }

    @RequestMapping(value = "/export", method = {RequestMethod.POST, RequestMethod.GET})
    @ApiOperation(value = "导出所选退货入库单")
    @FastMappingInfo(needLogin = true,code = AuthCode.ClientApply.RETURN_APPLY_EXPORT)
    public void export(String[] returnInIds) throws Exception
    {
        returnApplyService.export(Arrays.asList(returnInIds));
    }

    /**
     * 对外提供添加接口
     *
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/addReturnApply", method = RequestMethod.POST)
    public ActionResult addReturnApply(@RequestBody SalesReturnApplyAddVO model) throws Exception {
        LogHelper.monitor("addReturnApply接口入参：" + model.toString());
        ActionResult result = null;
        try {
            externalParamCheckService.checkParam(fillNeedCheckParam(model));
            result = returnApplyService.add(model);
        } catch (Exception e) {
            return actionResult(ErrorCode.Failure, e.getMessage());
        }
        return result;
    }

    private ExternalParamCheckVO fillNeedCheckParam(SalesReturnApplyAddVO model) throws Exception {
        CompanyInfoDO company = companyInfoMapper.item(saleIntentionMapper.selectSupplierOrgIdByNo(model.getSaleNo()));
        if (null == company) {
            throw new Exception("未查询到公司信息");
        }
        ExternalParamCheckVO param = new ExternalParamCheckVO();
        param.setSaleNo(model.getSaleNo());
        param.setSapCode(company.getSapCode());
        return param;
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ApiOperation(value = "添加退货申请")
    @FastMappingInfo(needLogin = true,code = AuthCode.ClientApply.RETURN_APPLY_ADD)
    public ActionResult add(@RequestBody SalesReturnApplyAddVO applyAddVO) throws Exception
    {
        applyAddVO.setUserId(getUserId());
        applyAddVO.setUserName(getUserName());
        applyAddVO.setDeptName(getDeptName());
        try {
            return actionResult(returnApplyService.addApply(applyAddVO));
        }catch (Exception e){
            return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
        }

    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ApiOperation(value = "添加退货申请")
    @FastMappingInfo(needLogin = true)
    public ActionResult update(@RequestBody SalesReturnApplyAddVO applyAddVO) throws Exception
    {
        try {
            return actionResult(returnApplyService.update(applyAddVO, null));
        }catch (Exception e){
            return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
        }

    }

    @RequestMapping(value = "/manulAdd", method = RequestMethod.POST)
    @ApiOperation(value = "根据零件添加退货申请")
    @FastMappingInfo(needLogin = true,code = AuthCode.ClientApply.RETURN_APPLY_MANUL_ADD)
    public ActionResult manulAdd(@RequestBody SalesReturnApplyAddVO applyAddVO) throws Exception
    {
        if(applyAddVO == null){
            return actionResult(ErrorCode.IllegalArument);
        }
        applyAddVO.setUserId(getUserId());
        applyAddVO.setUserName(getUserName());
        applyAddVO.setDeptName(getDeptName());
        return actionResult(returnApplyService.manulAdd(applyAddVO, getOrgId()));
    }

    @RequestMapping(value = "/manulUpdate", method = RequestMethod.POST)
    @ApiOperation(value = "更新退货申请")
    @FastMappingInfo(needLogin = true)
    public ActionResult manulUpdate(@RequestBody SalesReturnApplyAddVO applyAddVO) throws Exception
    {
        if(applyAddVO == null){
            return actionResult(ErrorCode.IllegalArument);
        }
        return actionResult(returnApplyService.manulUpdate(applyAddVO));
    }

    @RequestMapping(value = "/manulAudit", method = RequestMethod.POST)
    @ApiOperation(value = "更新退货申请")
    @FastMappingInfo(needLogin = true)
    public ActionResult manulAuditReturnApply(@RequestBody SalesReturnApplyAddVO applyAddVO) throws Exception
    {
        if(applyAddVO == null){
            return actionResult(ErrorCode.IllegalArument);
        }
        return actionResult(returnApplyService.manulAuditReturnApply(applyAddVO, getUserId(), getUserName()));
    }

    @ResponseBody
    @RequestMapping(value = "/import", method = RequestMethod.POST)
    @ApiOperation("零件批量导入")
    @FastMappingInfo(needLogin = true)
    public ActionResult importExcel(HttpServletRequest request) throws Exception{
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile(multipartRequest.getFileNames().next());
        String fileName = file.getOriginalFilename();
        FunctionResult<String> result=new FunctionResult<>();
        if (!fileName.trim().endsWith(".xls")) {
            result.setCode(ErrorCode.ImportExcelEndWithXLS);
        } else {
            InputStream in = file.getInputStream();
            result= returnApplyService.importExcel(in, request.getParameter("x-dealerOrgId"), getOrgId());
        }
        return actionResult(result.getCode(), result.getValue());
    }

    @RequestMapping(value = "/download",method = RequestMethod.POST)
    @ApiOperation("下载零件批量导入模板")
    @FastMappingInfo(needLogin = true)
    public void download() throws Exception {
        returnApplyService.download();
    }
}
